package cn.cloud9.designpattern.dp05proxy.proxy_03_jdk_dynamic.proxy_jdk;

import cn.cloud9.designpattern.dp05proxy.proxy_01_static.Tenement;
import cn.cloud9.designpattern.dp05proxy.proxy_03_jdk_dynamic.proxy_pack.MyClassLoader;
import cn.cloud9.designpattern.dp05proxy.proxy_03_jdk_dynamic.proxy_pack.MyProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author OnCloud9
 * @description
 * @project Java
 * @date 2022年05月23日 22:32
 */
public class MyHandler implements InvocationHandler {

    private Tenement target;

    public Tenement getInstance(Tenement tenement) {
        this.target = tenement;
        final Class<? extends Tenement> aClass = tenement.getClass();
        return (Tenement) Proxy.newProxyInstance(
            aClass.getClassLoader(),
            aClass.getInterfaces(),
            this
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        beforeAction();
        final Object invoke = method.invoke(this.target, args);
        afterAction();
        return invoke;
    }

    private void beforeAction() {
        System.out.println("代理实例前置处理");
    }

    private void afterAction() {
        System.out.println("代理实例后置处理");
    }
}
